package com.xxj.duck;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.util.Log;
import android.view.View;

import com.tencent.mobwin.AdView;

public class AdManager implements Runnable {

	private Activity gameActivity;

	private Map<Integer, Integer> dialogIDs;

	public AdManager(Activity gameActivity) {
		super();
		this.gameActivity = gameActivity;
		this.initIDs();
	}

	@SuppressLint("UseSparseArrays")
	private void initIDs() {
		dialogIDs = new HashMap<Integer, Integer>();
		dialogIDs.put(R.id.saveScoreDialog, View.GONE);
		dialogIDs.put(R.id.scoreRankDialog, View.GONE);
		dialogIDs.put(R.id.restartDialog, View.GONE);
		dialogIDs.put(R.id.settingsDialog, View.GONE);
		dialogIDs.put(R.id.backMenuDialog, View.GONE);
	}

	@Override
	public void run() {
		while (true) {
			try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			Iterator<Entry<Integer, Integer>> itr = dialogIDs.entrySet()
					.iterator();
			while (itr.hasNext()) {
				Entry<Integer, Integer> dialogID = itr.next();
				if (gameActivity != null && dialogID != null) {
					try {
						View view = gameActivity
								.findViewById(dialogID.getKey());
						if (view != null) {
							int state = view.getVisibility();
							if (state == View.VISIBLE
									&& dialogID.getValue() == View.GONE) {
								showHideAds(gameActivity, true);
							} else if (state == View.GONE
									&& dialogID.getValue() == View.VISIBLE) {
								showHideAds(gameActivity, false);
							} else {
								// Log.i("ads", " not to show/hide ads...");
							}
							dialogIDs.put(dialogID.getKey(), state);
						}
					} catch (Exception ex) {
						
					}
				}
			}
		}
	}

	public static void showHideAds(final Activity gameActivity,
			final boolean show) {
		Log.i("Prepare to show/hide ads", show + "");
		gameActivity.runOnUiThread(new Thread() {
			@Override
			public void run() {
				final AdView ad = (AdView) gameActivity
						.findViewById(R.id.adview);
				if (ad != null) {
					ad.setVisibility(show ? View.VISIBLE : View.GONE);
					Log.i("Ad status", show ? "[show]" : "[hide]");
				} else {
					Log.i("Ad status", " Ad is NULL.");
				}
			}
		});
	}

}
